package com.example.personalaccount.service.impl;

import com.example.personalaccount.dto.AccountDto;
import com.example.personalaccount.entity.Account;
import com.example.personalaccount.entity.User;
import com.example.personalaccount.handler.SecurityGetUserUtil;
import com.example.personalaccount.repository.AccountRepository;
import com.example.personalaccount.repository.UserRepository;
import com.example.personalaccount.service.AccountService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

@Service("accountService")
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountRepository accountRepository;

    @Autowired
    private SecurityGetUserUtil securityGetUserUtil;

    @Autowired
    private UserRepository userRepository ;

    @Override
    public Account getAccount(String id) {
        return accountRepository.findById(id).orElse(null);
    }

    @Override
    public Account getAccountByUserId(long id) {
        return  accountRepository.getAccountByUserId(id);
    }

    @Override
    public Account update(AccountDto accountDto) {
        Account account = accountRepository.getAccountByUserId(accountDto.getUserId());
        if (account == null) throw new RuntimeException("Account not found");
        account.setAccounts(accountDto.getAccounts());
        account.setExpends(accountDto.getExpends());
        return accountRepository.save(account);
    }

    @Override
    public Account addAccount(String function, String account) {
        User user = securityGetUserUtil.getUser();
        Account account1 = accountRepository.getAccountByUserId(user.getId());
        if (account1.getAccounts().containsKey(function))
        {
            if (account1.getAccounts().get(function).equals(account))
                throw new RuntimeException("is already account");
            int index = 1;
            while(account1.getAccounts().containsKey(function+index))
            {
                if (account1.getAccounts().get(function+index).equals(account))
                    throw new RuntimeException("is already account");
                index++;
            }
            account1.getAccounts().put(function+index, account);
        }
        else  account1.getAccounts().put(function, account);
        return accountRepository.save(account1);
    }

    @Override
    public Account removeAccount(String function, String account) {
        User user = securityGetUserUtil.getUser();
        Account account1 = accountRepository.getAccountByUserId(user.getId());
        account1.getAccounts().remove(function, account);
        return accountRepository.save(account1);
    }


}
